package com.camerax.sample

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.app.ActivityCompat
import com.camerax.sample.base.BaseActivity
import com.camerax.sample.databinding.ActivityMainBinding

/**
 * date        ：2020/11/30
 * author      ：秦川小将
 * description ：
 */
class MainActivity : BaseActivity<ActivityMainBinding>(), ActivityCompat.OnRequestPermissionsResultCallback, View.OnClickListener {

    private var takePictureUri: Uri? = null
    private var isUseSystemCamera = false
    private val activityResultLauncher = registerForActivityResult(ActivityResultContracts.TakePicture()) {
        Log.e(javaClass.simpleName, "结果：${takePictureUri}")
    }

    override fun layoutResId() = R.layout.activity_main

    override fun initView() {}

    override fun loadData() {

    }

    override fun onClick(v: View?) {
        when(v?.id) {
            R.id.use_camerax_take_picture -> {
                isUseSystemCamera = true
                takePicture()
            }
            R.id.use_system_camera_take_picture -> {
                isUseSystemCamera = false
                takePicture()
            }
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 200) {
            val result = grantResults.any { it != PackageManager.PERMISSION_GRANTED }
            if (!result) {
                takePicture()
            }
        }
    }

    private fun takePicture() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val checkWriteExternalStorage = CameraCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
            val checkReadExternalStorage = CameraCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
            val checkCamera = CameraCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
            if (checkWriteExternalStorage && checkReadExternalStorage && checkCamera) {
                if (!isUseSystemCamera) {
                    val mediaUri = if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) MediaStore.Images.Media.EXTERNAL_CONTENT_URI else MediaStore.Images.Media.INTERNAL_CONTENT_URI
                    takePictureUri = contentResolver.insert(mediaUri, CameraCompat.getContentValues())
                    activityResultLauncher.launch(takePictureUri)
                } else {
                    startActivity(Intent(this, CameraXActivity::class.java))
                }
            } else {
                requestPermissions(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA), 200)
            }
        } else {
            val mediaUri = if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) MediaStore.Images.Media.EXTERNAL_CONTENT_URI else MediaStore.Images.Media.INTERNAL_CONTENT_URI
            takePictureUri = contentResolver.insert(mediaUri, CameraCompat.getContentValues())
            activityResultLauncher.launch(takePictureUri)
        }
    }
}